// rbac.js
const roles = require('../config/roles.json');

class RBAC {
  constructor() {
    this.roles = roles.roles;
    this.permissions = roles.permissions;
  }

  // 检查用户是否有指定权限
  hasPermission(userRole, permission) {
    const role = this.roles.find(r => r.id === userRole);
    if (!role) return false;
    return role.permissions.includes(permission);
  }

  // 检查用户是否有多个权限中的任意一个
  hasAnyPermission(userRole, permissions) {
    return permissions.some(permission => this.hasPermission(userRole, permission));
  }

  // 检查用户是否有所有指定的权限
  hasAllPermissions(userRole, permissions) {
    return permissions.every(permission => this.hasPermission(userRole, permission));
  }

  // 获取角色的所有权限
  getRolePermissions(roleId) {
    const role = this.roles.find(r => r.id === roleId);
    return role ? role.permissions : [];
  }

  // 获取权限详情
  getPermissionDetails(permissionId) {
    return this.permissions.find(p => p.id === permissionId);
  }

  // 检查是否是管理员
  isAdmin(userRole) {
    return userRole === 'admin';
  }

  // 检查是否是商家
  isMerchant(userRole) {
    return userRole === 'merchant';
  }

  // 检查是否是普通用户
  isUser(userRole) {
    return userRole === 'user';
  }
}

const rbac = new RBAC();
module.exports = rbac; 